#!/usr/bin/env python

"""\
Read ENVISAT product file and output RDF/XML. The serialized version is
printed on the standard output unless an upload URL is given, in which
case it is sent as the body of an HTTP POST request to the given URL.
"""
__version__ = "$Id: $"
__usage__ = """
%prog [options] filename\
"""

from sys import exit
from os import stat
import urllib2
from duetopia.envisat import EnvisatProduct, EnvisatOptions, EnvisatConfig, EnvisatModel

if __name__ == '__main__':
	op = EnvisatOptions(version=__version__, description=__doc__,
				usage=__usage__)
	op.add_option("-f", "--flush",
			help="Flush any existing data about this file (destructive) [default False]",
			action="store_true",
			default=False,
	)
	op.add_option("-s", "--save",
			help="Save into the TripleStore [default False]",
			action="store_true",
			default=False,
	)
	op.add_option("-u", "--upload",
			help="Upload serialized RDF/XML to URL",
			action="store",
			default=False
	)

        (options, args) = op.parse_args()
        config = EnvisatConfig(options)

	if len(args) > 1:
		op.print_usage()
		exit()
	elif len(args) == 1:
		filename = args[0]
		stat(filename)

	prod = EnvisatProduct(config, args[0])
	data = prod.xml.serialize("utf-8", 1)

	if not options.upload:
		print data

	if options.flush or options.save:
		model = EnvisatModel(config)
	if options.flush:
		prod.flush(model)
	if options.save:
		prod.parse_into_model(model)
	if options.upload:
		request = urllib2.Request(options.upload, data)
		fp = urllib2.urlopen(request)
		response = fp.read()
		if response:
			print response
		fp.close()
